package com.doctor.windflower_doctor.adapter;

import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.actionBeen.UserControlBeen;
import com.doctor.windflower_doctor.activity.SickDetailActivity;
import com.doctor.windflower_doctor.activity.TenantService;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.entity.UserBeen;
import com.doctor.windflower_doctor.http.parser.impl.JsonHelper;
import com.doctor.windflower_doctor.myuser.tools.HttpclientHelper;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.view.PullToCustomListView;
import com.doctor.windflower_doctor.view.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class TenantServiceAdapter extends BaseAdapter implements Constent {

	private Context context;
	private List<UserBeen> list;
	private DialogueMoveAdapter moveAdapter;
	private int i = 0;
	private Dialog dialog;
	private boolean isShow;
	private List<String> addList;
	private Button moveButton;
	private DisplayImageOptions options;
	private SharedPreferencesDB db;
	private List<UserControlBeen> groupName;

	public boolean isShow() {
		return isShow;
	}

	public UserBeen getPosition(int position) {
		return list.get(position);
	}

	public void listClear() {
		list.clear();
	}

	public void setShow(boolean isShow) {
		this.isShow = isShow;
		notifyDataSetChanged();
	}

	public TenantServiceAdapter(final Context context, List<UserBeen> list,
			final List<UserControlBeen> groupName, Button moveButton) {
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.loading_img)
				.showImageOnFail(R.drawable.list_default_icon)
				.showImageForEmptyUri(R.drawable.list_default_icon)
				.cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888).build();
		db = SharedPreferencesDB.getInstance(context);
		this.moveButton = moveButton;
		this.context = context;
		this.list = list;
		this.groupName = groupName;
		moveAdapter = new DialogueMoveAdapter(groupName, context);
		addList = new ArrayList<String>();

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public void listAddAll(List<UserBeen> list) {
		this.list.addAll(list);
		notifyDataSetChanged();

	}

	public void removeList(int position) {
		list.remove(position);
		notifyDataSetChanged();

	}

	public List<UserBeen> getlist() {
		return list;

	}

	public void listAddOne(List<UserBeen> list) {
		this.list.addAll(0, list);
		notifyDataSetChanged();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ImageItemHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.groupuser_itme, null);
			holder = new ImageItemHolder();
			holder.imageView = (RoundedImageView) convertView
					.findViewById(R.id.img_imageView);
			holder.age = (TextView) convertView.findViewById(R.id.age_textView);
			holder.name = (TextView) convertView
					.findViewById(R.id.nick_textView);
			holder.pregnancy = (TextView) convertView
					.findViewById(R.id.pregnancy_textView);
			holder.checkBox = (CheckBox) convertView
					.findViewById(R.id.list_checkbox);

			convertView.setTag(holder);
		} else {
			holder = (ImageItemHolder) convertView.getTag();
		}
		SystemApplication.getInstance().mImageLoad1.displayImage(
				list.get(position).getImgUrl(), holder.imageView, options);
		holder.checkBox.setChecked(list.get(position).isFlag());
		holder.age.setText(list.get(position).getAge());
		holder.name.setText(list.get(position).getNick());
		holder.pregnancy.setText(list.get(position).getPrePeriod());

		if (isShow) {

			holder.checkBox.setVisibility(View.VISIBLE);
			moveButton.setVisibility(View.VISIBLE);
			convertView.setOnClickListener(new CheckOnclick(holder.checkBox,
					position));

		} else {

			holder.checkBox.setVisibility(View.INVISIBLE);
			moveButton.setVisibility(View.INVISIBLE);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(context,
							SickDetailActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("userId", list.get(position).getUserId());
					intent.putExtras(bundle);
					context.startActivity(intent);

				}
			});

		}

		return convertView;
	}

	class UserMessage_Asynck_Move extends AsyncTask<String, Void, String> {

		private String groupId;

		private String[] userIds_Array;

		public UserMessage_Asynck_Move(List<String> userIds, String groupId) {
			userIds_Array = new String[userIds.size()];

			this.groupId = groupId;

			userIds.toArray(userIds_Array);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			return HttpclientHelper.move(userIds_Array, groupId, params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {

				if (JsonHelper.userControl_Delete_Json(result).equals("true")) {

					for (int i = 0; i < list.size();) {
						if (list.get(i).isFlag()) {

							removeList(i);
						} else {
							i++;
						}
					}
					i = 0;
					moveButton.setText("移动");
					addList.clear();
				}

			} else {
				Toast.makeText(context, "请检查网络状态", Toast.LENGTH_SHORT).show();
			}
		}

	}

	class ImageItemHolder {
		private RoundedImageView imageView;
		private TextView name;
		private TextView age;
		private TextView pregnancy;
		private CheckBox checkBox;
	}

	class CheckOnclick implements OnClickListener {
		CheckBox checkBox;
		int position;

		CheckOnclick(CheckBox checkBox, int position) {
			this.checkBox = checkBox;
			this.position = position;

		}

		@Override
		public void onClick(View v) {

			if (checkBox.isChecked()) {
				addList.remove(list.get(position).getUserId());

				checkBox.setChecked(false);
				list.get(position).setFlag(false);
				i--;
				moveButton.setText("移动" + "(" + i + ")");

			} else {

				checkBox.setChecked(true);
				addList.add(list.get(position).getUserId());
				i++;

				moveButton.setText("移动" + "(" + i + ")");
				list.get(position).setFlag(true);
			}
			moveButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (groupName.size() == 0) {
						Toast.makeText(context, "您没有其他分组", Toast.LENGTH_SHORT)
								.show();
					} else {

						dialog = new Dialog(context);
						dialog.getWindow().setBackgroundDrawableResource(
								R.color.transparent);
						dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						View view = LayoutInflater.from(context).inflate(
								R.layout.move_dialogue, null);
						dialog.setContentView(view);
						ListView listView = (ListView) view
								.findViewById(R.id.dialogue_listView);
						listView.setAdapter(moveAdapter);

						listView.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// TODO Auto-generated method stub
								if (addList.size() == 0) {
									Toast.makeText(context, "请选择要移动的用户",
											Toast.LENGTH_SHORT).show();
									dialog.dismiss();
								} else {
									moveAdapter.setPosition(position);
									new UserMessage_Asynck_Move(addList,
											groupName.get(position).getId())
											.execute(URL + MOVE_URL
													+ db.getDocotorId());
									dialog.dismiss();
									notifyDataSetChanged();
								}

							}
						});

						dialog.show();
					}
				}
			});
		}

	}
}
